
import { HEADER, baseURL } from '../config'
import { wxAutoLogin, isAuthorize } from '../utils/wxutil'
import { Tips } from '../utils/util'
import axios from 'wx-axios-promise'
import Toast from '../components/weapp/toast/toast';
let app = {}
const service = axios({
    url: baseURL,
    header: HEADER
})
let index = 0
async function login() {
    let isAuth = await isAuthorize()
    console.log(isAuth)
    if(!isAuth) {
        wx.navigateTo({
        			url: '/pages/login/login'
        		})
    }
    if (index <= 0) {
        index++
        wxAutoLogin().then(res => {
            if (res.code == 200) {
                index = 0
console.log(res.data)
                wx.setStorageSync('token', res.data.access_token)
                wx.setStorageSync('nickname', res.data.member.nickname)
                wx.setStorageSync('avatar', res.data.member.image)
                 wx.setStorageSync('userInfo', res.data.member)
                let page = getCurrentPages()
                 console.log(page)
                app = getApp()
                app.store.setState({
                    isLogin: true,
                });
                page[page.length - 1].onLoad()
                page[page.length - 1].onShow()
            }
        })
    }

}
service.interceptors.request.use(config => {
    let token = wx.getStorageSync("token")
    
    if(token){
        config.header.Authorization = 'Bearer '+token
    }else{
    config.header.Authorization = 'Bearer '
    }
    //config.data.storeId = 0
    return config
}, () => {

})
service.interceptors.response.use(
    async response => {
console.log(response)

       if(response.statusCode == 502 || response.statusCode == 500) {
        //    return Tips({ title: '系统错误' })
       }
       if(response.statusCode == 401 ) {
        wx.navigateTo({
               			url: '/pages/login/login'
               		})
               		return;
         }
        if (response.data) {
            const { code, show, msg } = response.data
            if (code == 500) {
                if (msg) {
                    Tips({ title: msg })
                }
            } else if (code == -1) {
                app = getApp()
                app.store.setState({
                    isLogin: false,
                });
                login()
            }
            return Promise.resolve(response.data)

        }

    }, error => {
        console.log(error)
        return Promise.reject(error)
    })
export default service 